package study.chapter03.thread.model;

//生产者与消费者模型
public class TestThread {
    public static void main(String[] args) {
        Bread bread = new Bread();
        new Thread(new Producer(bread), "生产者线程").start();
        new Thread(new Consumer(bread), "消费者线程").start();
    }
}

//面包类
class Bread{
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Bread{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

//生产者
class Producer implements Runnable{
    private Bread bread;
    Producer(Bread bread){
        this.bread = bread;
    }

    @Override
    public void run() {
        System.out.println("开始生产面包");
        for (int i = 1; i <= 10; i++) {
            bread.setId(i);
            bread.setName("面包" + i);
            System.out.println("生产面包：" + bread);

            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者
class Consumer implements Runnable{
    private Bread bread;
    Consumer(Bread bread){
        this.bread = bread;
    }

    @Override
    public void run() {
        System.out.println("开始消费面包");
        for (int i = 0; i < 5; i++) {
            System.out.println("消费面包：id=" + bread.getId() + "，" + bread.getName());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
